/**
 @author Jacye.Ouyang
 */
/*Dependence: essential:GOLBAL_DATA; optional: gExchangeMap,gMICExangeMap */
/* control permission of accessing data from push server the exchanges */

if(!QS) {
    var QS = {};
}

QS.PermissionChecker = function(permissionData,gExchMap,gMICMap){   // the permission data is from GOLBAL_DATA
    this.dataPermission = {1:{},10:{},20:{},8:{},3:{},7:{},9:{},11:{},16:{},13:{},2:{}};  
    this.modulePermission = {};
	this.exchangePermission ={};
    this.securityTypes = [1,10,3,20,2,8,7,9,11,16,13,3]; // 1:ST,ETF and CE; 10:index;
	this.subUSExchange = [41,11,9,30,29,33,22,25];
	this.MICToExchangeID= {};
    this._init(permissionData,gExchMap,gMICMap);
};
QS.PermissionChecker.prototype = {
    _init:function(permissionData,gExchMap,gMICMap){
        var tExchMap = this._initDataPermission(permissionData.DataPermission);  
		this.exchangePermission= tExchMap;
        this._initACBExchMap(gExchMap,gMICMap);
    },
    _initDataPermission:function(data){
        var  tExchMap = {};
        if(data && data.length) {
            var idxs,secList = [],exch,type,code,idx;
            for(var i = 0; i < data.length;i++){
                secList = data[i]["sec"].replace(/,$/,"").split(","), exch = data[i]["exch"],
                type = data[i]["type"],code = data[i]["code"].replace(/,$/,"").split(","),ckidx = data[i]["ckIdx"];
                tExchMap[exch] = true;
                if(data[i]["sec"]== "-1"){ // index, stock,ETF and CE                // not index
                    if(!this.dataPermission[1][exch]){
                        this.dataPermission[1][exch] = {}
                    }
                    if(!this.dataPermission[10][exch]){
                        this.dataPermission[10][exch] = {}
                    }
                    if(!this.dataPermission[8][exch]){
                        this.dataPermission[8][exch] = {}
                    }
					if(!this.dataPermission[7][exch]){ // bond
                        this.dataPermission[7][exch] = {}
                    }
                    if(!this.dataPermission[9][exch]){// bond
                        this.dataPermission[9][exch] = {}
                    }
                    if(!this.dataPermission[11][exch]){// bond
                        this.dataPermission[11][exch] = {}
                    }
					if(!this.dataPermission[16][exch]){// bond
                        this.dataPermission[16][exch] = {}
                    }
					if(!this.dataPermission[13][exch]){// bond
                        this.dataPermission[13][exch] = {}
                    }//Spread
					if(!this.dataPermission[3][exch]){// bond
                        this.dataPermission[3][exch] = {}
                    }//Future
					if(!this.dataPermission[2][exch]){// bond
                        this.dataPermission[2][exch] = {}
                    }//Options*/
                    this.dataPermission[1][exch][type] = {code:code};
                    this.dataPermission[10][exch][type] = {code:code};
                    this.dataPermission[8][exch][type] = {code:code};
					this.dataPermission[7][exch][type] = {code:code};
                    this.dataPermission[9][exch][type] = {code:code};
                    this.dataPermission[11][exch][type] = {code:code};
					this.dataPermission[16][exch][type] = {code:code};
					this.dataPermission[13][exch][type] = {code:code};
					this.dataPermission[2][exch][type] = {code:code};
					this.dataPermission[3][exch][type] = {code:code};
                } else {   // other security type.
                    for(var j=0;j<secList.length;j++){
                        if(typeof(secList[j])=="undefined"||secList[j]=="") continue;
                        if(!this.dataPermission[secList[j]])this.dataPermission[secList[j]]= {};
                        if(!this.dataPermission[secList[j]][exch])this.dataPermission[secList[j]][exch]= {};
                        this.dataPermission[secList[j]][exch][type] = {code:code};
                        if(ckidx == 1){ // check the ticker in one exch.
                            this.dataPermission[secList[j]][exch][type] = {code:code,idx:data[i]["idx"].replace(/,$/,"").split(",")};
                        }     
                    }
                }
            }
            this.dataPermission[20]["245"] = {};
            this.dataPermission[20]["245"]["D"]={code:[-1]};  // add forex exchanges in permission.
            this.dataPermission[20]["240"] = {};
            this.dataPermission[20]["240"]["D"]={code:[-1]};  
            this.dataPermission[3]["64"] = {"D":{code:[-1]}};// add furture exchanges in permission.
            this.dataPermission[3]["66"] = {"D":{code:[-1]}};
            this.dataPermission[3]["67"] = {"D":{code:[-1]}};
            this.dataPermission[3]["77"] = {"D":{code:[-1]}}; 
            this.dataPermission[10]["27"] = {"D":{code:[-1]}}; // MSCI Indexs.
			this.dataPermission[10]["41"] = {"D":{code:[-1]}}; //indices.
        }
        return tExchMap;
    },
    getDataSource:function(exch,sectype,subcode){
        var sourcelist=this.dataPermission[sectype][exch];
        if(typeof subcode!="undefined"){
            for(var sourcetype in sourcelist){
                if($.inArray(subcode,sourcelist[sourcetype])!=-1){
                    return sourcetype;
                }
            }
        }else{
            return "R" in sourcelist?"R":"D";
        }
    },
    _initACBExchMap:function(gExchMap,gMICMap){
        if (typeof(gExchMap) == "undefined" || typeof(gMICMap) == "undefined") return;
        //gExchMap  tenforExchangeID -> shortName
        //gMICMap   MIC -> shortName
        //tExchMap  tenforExchangeID power
		var shortNameToMIC={},shortNameToExch={};
		for (var ii in gMICMap) {//
			if (gMICMap[ii] != "") {
				shortNameToMIC[gMICMap[ii]] = ii;
			}
		}
        for (var ex in gExchMap) {//
            if (gExchMap[ex] != "") {
                shortNameToExch[gExchMap[ex]] = ex;
            }
        }
        for(var shorN in shortNameToMIC){
            if(shortNameToExch[shorN]){
                this.MICToExchangeID[shortNameToMIC[shorN]]=shortNameToExch[shorN];
            }
        }
    },
    /* provide interface to get the subcodes to subscribe data from Push or Pull server*/
    /* sType: tenfore security type. tExchange: tenfore exchange code, tTicker: tenfore Ticker,dataType:"D" or "R".*/
    getSubcodes:function(sType,tExchange,tTicker,dataType){  
        var subcode = [];
        if(this.dataPermission[sType]&&this.dataPermission[sType][tExchange]&&this.dataPermission[sType][tExchange][dataType]){
            if(sType==10&&this.dataPermission[sType][tExchange][dataType]["idx"]){// index need check the ticker is in the idx list
                if($.inArray(tTicker,this.dataPermission[sType][tExchange][dataType]["idx"])>-1){
                    subcode = this.dataPermission[sType][tExchange][dataType]["code"];
                }
            }else{
                subcode = this.dataPermission[sType][tExchange][dataType]["code"];
            }   
        }
        return subcode;
    },
    /* provide interface for auto-complete component to check permission */
    /*check the permission using MIC Code such as: XTSE,XNYS,XNAS. For USA security, you can use country id.*/
    checkACBPermission:function(micCode,exchId,securityType){
        var exchEntitlement=false;
		if(typeof(exchId)!="undefined"&&exchId!=""){
			exchEntitlement = this.exchangePermission[exchId]||false;
		}else{
            if(this.MICToExchangeID[micCode]){
                exchEntitlement = this.exchangePermission[this.MICToExchangeID[micCode]]||false;
            }
        }
        if(exchEntitlement&&typeof(exchId)!="undefined"&&exchId!=""&&typeof(securityType)!="undefined"&&securityType!=""){
            return this.dataPermission[securityType][exchId]||false;
        }
        return exchEntitlement;
    },
	/** provide interface for ticker object check permission **/	
	/** tickerObject is a instance of QSAPI.Ticker**/
	checkTickerObjectPremission:function(tickerObject){
		var eCode=tickerObject.getField("tenforeCode"),
			type=parseInt(tickerObject.getField("type"),10),
			tTicker=tickerObject.getField("tenforeTicker"),
			exchCode = "";
		/*check if the ticker is R permission using the real sub exchange*/	
		var subcodes = this.getSubcodes(type,eCode,tTicker,"R");
		if(subcodes.length>0){// Clients will subscribe real-time if they have real-time data permission.
			if (((type==1||type==10||type==8||type==2)&& eCode<=126&&eCode != 50)) { // USA stock,MF,Options and index(use 126 as exchange to subscribe level I data.)
				if(eCode != 41&&eCode!=11&&eCode!=9&&eCode!=30&&eCode!=29&&eCode!=33){
					exchCode = "126"; // 11,41 exchange is removed from 126 exchange.
				}else{
					exchCode = eCode;
				}
				if(type!=10||type!=2){//option and index no need to get USCOMP exchange subcodes               
                    subcodes = this.getSubcodes(type,exchCode,tTicker,"R",false);  // get USCOMP exchange
                }
			}
		}else{
			if ((type==1||type==10||type==8||type==2) && eCode<=126&& $.inArray(parseInt(eCode,10),this.subUSExchange)<0) { // USA stock,MF, Options and index(use 126 as exchange to subscribe level I data.)
				exchCode = "126"; 
			}else {
				exchCode = eCode;
			}
			if(type==2){
				subcodes = this.getSubcodes(type,eCode,tTicker,"D",false);  // get individual exchange subcodes when it is option
			}else{
				subcodes = this.getSubcodes(type,exchCode,tTicker,"D",false);  // get USCOMP exchange
			}
		}		
		if(subcodes.length>0){
			return true;
		}else{
			return false;
		}
	}
};
/*
QS.Permission = new QS.PermissionChecker(GOLBAL_DATA,gExchangeMap,gMICExangeMap);  // 
delete GOLBAL_DATA.DataPermission;  // delete it from GOLBAL_DATA object.*/
   